# import sys
# sys.path.append('H:\llmapp')
import json

import easyocr
import torch

from util.T2util import NumpyJSONEncoder
from transformers import AutoTokenizer, AutoModelForCausalLM, CLIPImageProcessor, CLIPVisionModel
from PIL import Image
import numpy as np
"""
使用gpu,需要使用以下命令安装
pip3 install torch torchvision torchaudio
:return 字典类型：
    text:str 文本,\n分隔 
    detail:list 详细信息, 含坐标
"""
"""
    # extract_text_from_image_easyocr
    # 检查 CUDA 是否可用
    print("CUDA 是否可用:", torch.cuda.is_available())
    调用函数并传入图片路径
    image_path = 'H:/llmapp/test_file/extract_text_from_image_easyocr.png'
    extracted_text = extract_text_from_image_easyocr(image_path)
    if extracted_text:
        print("提取的结果(文本):")
        print(extracted_text['text'])
        print("提取的结果(详细):")
        for item in extracted_text['detail']:
            print(json.dumps(item, cls=NumpyJSONEncoder, ensure_ascii=False))

    #extract_text_from_image_easyocr _______________________________________
"""
def extract_text_from_image_easyocr(image_path)->dict:
    try:
        # 创建一个 reader 对象，指定要识别的语言
        reader = easyocr.Reader(['ch_sim','en']
                                , model_storage_directory="D:\modelscope\easyocr"
                                , gpu= True
                                )
        # 读取图片并提取文字
        result = reader.readtext(image_path)
        # 提取识别到的文字
        text = '\n'.join([res[1] for res in result])
        return {
          "text":text,
          "detail":result
        }
    except Exception as e:
        print(f"发生错误: {e}")
        return {}


if __name__ == '__main__':
    # 检查 CUDA 是否可用
    print("CUDA 是否可用:", torch.cuda.is_available())
    # 调用函数并传入图片路径
    image_path = 'H:/llmapp/test_file/extract_text_from_image_easyocr.png'
    extracted_text = extract_text_from_image_easyocr(image_path)
    if extracted_text:
        print("提取的结果(文本):")
        print(extracted_text['text'])
        print("提取的结果(详细):")
        for item in extracted_text['detail']:
            print(json.dumps(item, cls=NumpyJSONEncoder, ensure_ascii=False))
